<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
	<title>角色管理</title>
	<%@include file="/WEB-INF/views/include/treeview.jsp" %>
	<script type="text/javascript">
		$(document).ready(function(){
			let _mainFrame = window.top.document.getElementById('mainFrame');
			const bodyHeight = $(_mainFrame).height();
			const headerHeight = $('.card-header').outerHeight(true) || 0;
			const ztreePadding = parseInt($('#menuTree').css('padding-top') || 0) + parseInt($('#menuTree').css('padding-bottom') || 0);
			$('#menuTree,#officeTree').height(bodyHeight - headerHeight - ztreePadding - 3);
			let h = bodyHeight - 40;
			console.log('bodyHeight: ',bodyHeight,'h: ',h)
			$('#card-body').height(h);

			$("#inputForm").validate({
				rules: {
					name: {remote: "${ctxAdmin}/sys/role/checkName?oldName=" + encodeURIComponent("${role.name}")},
					enname: {remote: "${ctxAdmin}/sys/role/checkEnname?oldEnname=" + encodeURIComponent("${role.enname}")}
				},
				messages: {
					name: {remote: "角色名已存在"},
					enname: {remote: "英文名已存在"}
				},
				submitHandler: function(form){
					var ids = [], nodes = tree.getCheckedNodes(true);
					for(var i=0; i<nodes.length; i++) {
						ids.push(nodes[i].id);
					}
					$("input[name='menuIds']").val(ids);
					var ids2 = [], nodes2 = tree2.getCheckedNodes(true);
					for(var i=0; i<nodes2.length; i++) {
						ids2.push(nodes2[i].id);
					}
					$("input[name='officeIds']").val(ids2);
					console.log(ids)
					console.log(ids2)
					form.submit();
				},
				errorContainer: "#messageBox",
				errorPlacement: function(error, element) {
					$("#messageBox").text("输入有误，请先更正。");
					if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
						error.appendTo(element.parent().parent());
					} else {
						error.insertAfter(element);
					}
				}
			});

			let setting = {check:{enable:true,nocheckInherit:true},view:{selectedMulti:false},
					data:{simpleData:{enable:true}},callback:{beforeClick:function(id, node){
						tree.checkNode(node, !node.checked, true, true);
						return false;
					}}};
			
			// 用户-菜单
			let zNodes=[
					<c:forEach items="${menuList}" var="menu">{id:"${menu.id}", pId:"${not empty menu.parent.id?menu.parent.id:0}", name:"${not empty menu.parent.id?menu.name:'权限列表'}"},
		            </c:forEach>];
			// 初始化树结构
			let tree = $.fn.zTree.init($("#menuTree"), setting, zNodes);
			// 不选择父节点
			tree.setting.check.chkboxType = { "Y" : "ps", "N" : "s" };
			// 默认选择节点
			var ids = "${role.menuIds}".split(",");
			for(var i=0; i<ids.length; i++) {
				var node = tree.getNodeByParam("id", ids[i]);
				try{tree.checkNode(node, true, false);}catch(e){}
			}
			// 默认展开全部节点
			tree.expandAll(true);
			
			// 用户-机构
			var zNodes2=[
					<c:forEach items="${officeList}" var="office">{id:"${office.id}", pId:"${not empty office.parent?office.parent.id:0}", name:"${office.name}"},
		            </c:forEach>];
			// 初始化树结构
			var tree2 = $.fn.zTree.init($("#officeTree"), setting, zNodes2);
			// 不选择父节点
			tree2.setting.check.chkboxType = { "Y" : "ps", "N" : "s" };
			// 默认选择节点
			var ids2 = "${role.officeIds}".split(",");
			for(var i=0; i<ids2.length; i++) {
				var node = tree2.getNodeByParam("id", ids2[i]);
				try{tree2.checkNode(node, true, false);}catch(e){}
			}
			// 默认展开全部节点
			tree2.expandAll(true);
			// 刷新（显示/隐藏）机构
			refreshOfficeTree();
			$("#dataScope").change(function(){
				refreshOfficeTree();
			});
		});
		function refreshOfficeTree(){
			if($("#dataScope").val()==9){
				$("#office-tree").show();
				// layerOpenRight();
			}else{
				$("#office-tree").hide();
			}
		}
		function layerOpenRight(){
			layer.open({
				type: 1,
				title: 'title',
				offset: 'r',
				anim: 'slideLeft', // 从右往左
				area: ['60%', '100%'],
				shade: 0.1,
				shadeClose: true,
				content: $('#officeTree')
			});
		}
	</script>
	<style>
		.ztree,#card-body{
			width: 100%;
			overflow: auto;
		}
	</style>
</head>
<body class="sidebar-right-visible">
<div class="page-content">
	<sys:message content="${message}"/>
	<div class="content-wrapper">
		<div class="content p-0">
			<div class="card border-0">
				<div id="card-body" class="card-body">
					<form:form id="inputForm" modelAttribute="role" action="${ctxAdmin}/sys/role/save" method="post" class="form-horizontal">
						<form:hidden path="id"/>
						<%--工作流组用户组类型（security-role：管理员、assignment：可进行任务分配、user：普通用户） 如果使用Activiti Explorer，需要security-role才能看到manage页签，需要assignment才能claim任务--%>
						<form:hidden path="roleType" value="user"/>
						<%--“1”代表此数据只有超级管理员能进行修改，“0”则表示拥有角色修改人员的权限都能进行修改--%>
						<form:hidden path="sysData" value="1"/>
						<%--“1”代表此数据可用，“0”则表示此数据不可用--%>
						<form:hidden path="useable" value="1"/>
						<input type="hidden" name="menuIds">
						<input type="hidden" name="officeIds">

						<div class="form-group row">
							<label class="col-sm-3 col-form-label"><span class="text-danger">*</span>排序</label>
							<div class="col-sm-9">
								<form:input path="sort" htmlEscape="false"  cssClass="required form-control"/>
							</div>
						</div>
						<div class="form-group row">
							<label class="col-sm-3 col-form-label">归属机构</label>
							<div class="col-sm-9">
								<sys:treeselect id="office" name="office.id" value="${role.office.id}" labelName="office.name" labelValue="${role.office.name}"
												title="机构" url="/sys/office/treeData" cssClass="required form-control" allowClear="true"/>
							</div>
						</div>
						<div class="form-group row">
							<label class="col-sm-3 col-form-label"><span class="text-danger">*</span>角色名称</label>
							<div class="col-sm-9">
								<input id="oldName" name="oldName" type="hidden" value="${role.name}">
								<form:input path="name" htmlEscape="false" maxlength="50" cssClass="required form-control"/>
							</div>
						</div>
						<div class="form-group row">
							<label class="col-sm-3 col-form-label"><span class="text-danger">*</span>英文名称</label>
							<div class="col-sm-9">
								<input id="oldEnname" name="oldEnname" type="hidden" value="${role.enname}">
								<form:input path="enname" htmlEscape="false" maxlength="50" cssClass="required form-control"/>
							</div>
						</div>
						<div class="form-group row">
							<label class="col-sm-3 col-form-label">数据范围</label>
							<div class="col-sm-9">
								<form:select path="dataScope" class="input-medium">
									<form:options items="${fns:getDictList('sys_data_scope')}" itemLabel="label" itemValue="value" htmlEscape="false"/>
								</form:select>
								<span class="help-inline">按明细设置，可进行跨机构授权</span>
							</div>
						</div>
						<div class="form-group row">
							<div class="col-sm-9 ml-auto">
								<c:if test="${(role.sysData eq fns:getDictValue('是', 'sys_yes_no', '1') && fns:getUser().admin)||!(role.sysData eq fns:getDictValue('是', 'sys_yes_no', '1'))}">
									<shiro:hasPermission name="sys:role:edit">
										<button type="submit" class="btn btn-primary" onclick="assign()"><i class="icon-database-check mr-2"></i>保 存</button>
										<a class="btn btn-light" href="${ctxAdmin}/sys/role/"><i class="icon-database-arrow mr-2"></i>取 消</a>
									</shiro:hasPermission>
								</c:if>
							</div>
						</div>
					</form:form>
				</div>
			</div>
		</div>
	</div>
	<div class="sidebar sidebar-light sidebar-right sidebar-expand-md" style="width: 300px;">
		<div class="sidebar-content">
			<div class="card">
				<div class="card-header bg-transparent header-elements-inline p-2">
					<span>权限授权</span>
				</div>
				<div class="card-body p-0">
					<div id="menuTree" class="ztree"></div>
				</div>
			</div>
		</div>
	</div>
	<div id="office-tree" class="sidebar sidebar-light sidebar-right sidebar-expand-md" style="width: 300px;">
		<div class="sidebar-content">
			<div class="card">
				<div class="card-header bg-transparent header-elements-inline p-2">
					<span>部门授权</span>
				</div>
				<div class="card-body p-0">
					<div id="officeTree" class="ztree"></div>
				</div>
			</div>
		</div>
	</div>
</div>
</body>
</html>